import React, { createContext, ReactElement } from 'react';
import { State, Action, Context, Item } from './types';
import actions, { getSelfCenter } from './actions';
import Provider from '../../../../components/Provider';
import { ITEMS } from './constant';

export const initialState: State = {
  items: ITEMS,
  data: {
    mobilePhone: '',
    headPortraitURL: '',
    nickName: '',
    gender: 0,
    goldCoinNum: 0,
    yutouCoinNum: 0
  },
  isFetchFailed: false
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'FETCH_SUCCESS': {
      const { items } = state;
      const currentItems = items.map(
        (item): Item => {
          if (item.title === '我的金币') {
            return {
              ...item,
              subTitle: `${action.value.goldCoinNum}枚`
            };
          }
          return item;
        }
      );

      return {
        ...state,
        items: currentItems,
        data: action.value,
        isFetchFailed: false
      };
    }
    case 'FETCH_FAILED':
      return { ...state, isFetchFailed: true };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      reload={getSelfCenter}
      {...props}
    />
  );
};
